package logic

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

// Activity 活动管理
type Activity interface {
	Lottery(userId int)
}

// GoodsInfo 奖品信息
type GoodsInfo struct {
	GoodsName string
	GoodsNum  int
	WinRate   int
	IsAccount int
}

// ActivityLottery 抽奖
type ActivityLottery struct {
}

var (
	awardsInfo = &[]GoodsInfo{
		{"苹果手机", 1, 1000, 1},
		{"HuaWeiMate60Pro", 1, 2000, 1},
		{"Ikun手办", 1, 6000, 1},
		{"谢谢参与", 1, 1000, 0},
	}
	mutex sync.Mutex
)

// Lottery 抽奖
func (a ActivityLottery) Lottery(userId int) {
	// 随机数种子，使用当前时间作为种子
	rand.Seed(time.Now().UnixNano())
	// 计算总中奖概率
	for {
		totalWinRate := 0
		for _, awards := range *awardsInfo {
			totalWinRate += awards.WinRate
		}
		// 生成一个随机数
		randNumber := rand.Intn(totalWinRate)
		// 中奖
		var winRate int
		for key, awards := range *awardsInfo {
			if winRate >= randNumber && awards.GoodsNum > 0 {
				// 加锁
				defer mutex.Unlock()
				mutex.Lock()
				if awards.IsAccount == 1 && awards.GoodsNum > 0 {
					awards.GoodsNum--
					(*awardsInfo)[key].GoodsNum = awards.GoodsNum
					fmt.Printf("恭喜 %d 抽中%s,----->奖品剩余:%d \n", userId, awards.GoodsName, awards.GoodsNum)
				} else {
					fmt.Printf("恭喜 %d 抽中%s !\n", userId, awards.GoodsName)
				}
				return
			}
			winRate += awards.WinRate
		}
	}
}

// MarketingManagement 营销活动
type MarketingManagement struct {
	HoldName string
	HoldType Activity
}

// SetActivityStrategy 设置活动策略
func (m *MarketingManagement) SetActivityStrategy(activity Activity) {
	m.HoldType = activity
}

// GetActivityStrategy 获取活动策略
func (m *MarketingManagement) GetActivityStrategy(userId int) {
	if m.HoldType == nil {
		return
	}
	m.HoldType.Lottery(userId)
}
